import { detectDevice, adjustInterfaceForDevice, isMobile } from './deviceDetection.js';
import { checkCameraAvailability, toggleCamera, stopCamera, takePhoto, resetCamera, currentPhotoData, cameraActive, resetProbabilityItems } from './cameraModule.js';
import { handleFiles, setupDropArea } from './fileUpload.js';
import { selectImageForAnalysis } from './imageAnalysis.js';
import { addTransitionAnimations, showToast, setupExampleImages } from './uiEffects.js';
import '../css/style.css';
import '../css/mobile.css';
import '../css/mobile-device.css';

// 页面元素
let elements = {};

// 初始化应用
function initApp() {

    // 获取DOM元素
    elements = {
        // 文件上传元素
        fileInput: document.getElementById('fileInput'),
        selectFileBtn: document.getElementById('selectFile'),
        dropArea: document.getElementById('dropArea'),
        tipsContent: document.getElementById('tipsContent'),
        
        // 摄像头元素
        video: document.getElementById('video'),
        canvas: document.getElementById('canvas'),
        toggleCameraBtn: document.getElementById('toggleCamera'),
        shutterBtn: document.getElementById('shutterBtn'),
        
        // 原生相机元素
        nativeCameraInput: document.getElementById('nativeCamera'),
        captureNativeBtn: document.getElementById('captureNative'),
        
        // 界面元素
        uploadContainer: document.querySelector('.upload-container'),
        exampleImageBtn: document.getElementById('exampleImageBtn')
    };

    // 检查网络连接
    checkNetworkConnection();
    
    // 检测设备类型
    detectDevice();
    
    // 调整界面
    adjustInterfaceForDevice(elements);
    
    // 检查摄像头可用性
    checkCameraAvailability(elements.toggleCameraBtn);
    
    // 设置事件监听器
    setupEventListeners();
    
    // 添加过渡动画
    addTransitionAnimations();
    
    // 设置示例图片功能
    setupExampleImages();
}

// 设置事件监听器
function setupEventListeners() {
    const { 
        selectFileBtn, 
        fileInput, 
        captureNativeBtn, 
        nativeCameraInput,
        dropArea,
        toggleCameraBtn,
        shutterBtn,
        video
    } = elements;
    
    // 点击选择文件按钮
    selectFileBtn.addEventListener('click', () => {
        stopCamera(elements);
        fileInput.click();
    });
    
    // 点击使用手机相册按钮
    captureNativeBtn.addEventListener('click', () => {
        stopCamera(elements);
        
        // 在移动端，设置为相册模式而非相机模式
        if (isMobile) {
            nativeCameraInput.removeAttribute('capture');
        }
        
        nativeCameraInput.click();
    });
    
    // 监听原生相机拍照结果
    nativeCameraInput.addEventListener('change', (e) => handleFiles(e, () => stopCamera(elements)));
    
    // 监听文件选择
    fileInput.addEventListener('change', (e) => handleFiles(e, () => stopCamera(elements)));
    
    // 设置拖放上传区域
    setupDropArea(dropArea, handleFiles, () => stopCamera(elements));
    
    // 摄像头开关按钮
    toggleCameraBtn.addEventListener('click', () => {
        toggleCamera(elements);
    });
    
    // 添加快门按钮事件监听
    if (shutterBtn) {
        shutterBtn.addEventListener('click', () => {
            if (cameraActive) {
                // 触发拍照
                takePhoto(elements);
                document.getElementById('shutterBtn').style.display = 'none';
                document.querySelector('.video-container').style.display = 'block';
                document.getElementById('photoConfirmControls').style.display = 'flex';
                document.getElementById('retakePhotoBtn').style.display = 'flex';
                document.getElementById('confirmPhotoBtn').style.display = 'flex';
                document.getElementById('backPhotoBtn').style.display = 'none';
                
            }
        });
    }

    // 添加确认和重拍按钮的事件监听
    const confirmPhotoBtn = document.getElementById('confirmPhotoBtn');
    const retakePhotoBtn = document.getElementById('retakePhotoBtn');
    if (confirmPhotoBtn) {
        confirmPhotoBtn.addEventListener('click', () => {
            if (currentPhotoData) {
                // 使用存储的照片数据进行分析
                selectImageForAnalysis(currentPhotoData.imageData, currentPhotoData.fileName);
            }
        });
    }
    if (retakePhotoBtn) {
        retakePhotoBtn.addEventListener('click', () => {
            resetCamera(elements)
        });
    }

    const backPhotoBtn = document.getElementById('backPhotoBtn');
    if (backPhotoBtn) {
        backPhotoBtn.addEventListener('click', () => {
            document.querySelector('.no-image-placeholder').style.display = 'flex';
            document.getElementById('selectedImage').style.display = 'none'
            document.getElementById('backPhotoBtn').style.display = 'none';
            resetProbabilityItems();
        });
    }

    // 示例图片点击事件
    const exampleImageItems = document.querySelectorAll('.example-image-item');
    exampleImageItems.forEach(item => {
        item.addEventListener('click', () => {
            const imagePath = item.getAttribute('data-image');
            
            // 关闭抽屉
            document.getElementById('exampleDrawer').classList.remove('open');
                        
            // 停止摄像头
            stopCamera(elements);
            
            // 加载示例图片
            fetch(imagePath)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('无法加载示例图片');
                    }
                    return response.blob();
                })
                .then(blob => {
                    // 创建临时URL
                    const imageUrl = URL.createObjectURL(blob);
                    
                    // 使用示例图片进行分析
                    selectImageForAnalysis(imageUrl, imagePath.split('/').pop());

                    // 显示视频容器和控制按钮
                    document.getElementById('shutterBtn').style.display = 'none';
                    document.querySelector('.video-container').style.display = 'block';
                    document.getElementById('photoConfirmControls').style.display = 'flex';
                    document.getElementById('retakePhotoBtn').style.display = 'none';
                    document.getElementById('confirmPhotoBtn').style.display = 'none';
                    document.getElementById('backPhotoBtn').style.display = 'block';

                    const retakePhotoBtn = document.getElementById('retakePhotoBtn');
                    if (retakePhotoBtn) {
                        const spanElement = retakePhotoBtn.querySelector('span');
                        if (spanElement) {
                            spanElement.textContent = '返回';
                        } else {
                            retakePhotoBtn.textContent = '返回';
                        }
                    }
                })
                .catch(error => {
                    console.error('加载示例图片失败:', error);
                    showToast('无法加载示例图片: ' + error.message, 'error');
                });
        });
    });
    
    // 添加示例图片按钮事件监听
    const exampleImageBtn = document.getElementById('exampleImageBtn');
    const exampleDrawer = document.getElementById('exampleDrawer');
    const closeDrawerBtn = document.getElementById('closeDrawerBtn');
    
    if (exampleImageBtn) {
        exampleImageBtn.addEventListener('click', () => {
            // 打开抽屉
            exampleDrawer.classList.add('open');
        });
    }
    
    // 关闭抽屉按钮
    if (closeDrawerBtn) {
        closeDrawerBtn.addEventListener('click', () => {
            exampleDrawer.classList.remove('open');
        });
    }
    
    // 检查屏幕方向变化
    window.addEventListener('orientationchange', () => {
        // 短暂延迟以确保方向变化完成
        setTimeout(() => {
            adjustInterfaceForDevice(elements);
            
            // 如果相机正在使用中，调整视频元素
            if (cameraActive) {
                video.style.height = 'auto';
            }
        }, 300);
    });
    
    // 添加全局进度条事件
    const progressBar = document.getElementById('global-progress');
    if (progressBar) {
        document.addEventListener('apiRequestStart', () => {
            progressBar.classList.add('active');
        });
        
        document.addEventListener('apiRequestEnd', () => {
            progressBar.classList.remove('active');
        });
    }
}

// 检查网络连接
function checkNetworkConnection() {
    if (!navigator.onLine) {
        showToast('网络连接已断开，部分功能可能无法使用', 'warning');
    }
    
    // 监听网络状态变化
    window.addEventListener('online', () => {
        showToast('网络连接已恢复', 'success');
    });
    
    window.addEventListener('offline', () => {
        showToast('网络连接已断开，部分功能可能无法使用', 'warning');
    });
}

// 导出需要的函数和变量
export { initApp, elements };
                